import Toast, { hideToast } from 'tdesign-miniprogram/toast'
const app = getApp()

Page({
  onShow() {
    wx.reportAnalytics('enter_user_detail_programmatically', {})
  },
  onShareAppMessage() {
    return {
      title: '用户详情',
      path: 'packageHome/pages/user-detail/index?openid=' + this.data.openid
    }
  },
  onShareTimeline() {
    '用户详情'
  },

  data: {
    theme: 'light',
    user: null,
    other: null,
    onGlobalUserChange: null,
    openid: '',

    loading: {loading: false},
    sh: '', // 键名仅有一个字母时无法model
    page: 1,
    size: 5,
    noMore: false,
    keyPost: {},
    posts: [],
    post: null,
    postActions: [],
  },

  onLoad({openid}) {
    if (openid) {
      this.data.openid = openid
      this.getUser()
      this.onSearch()
    }
    this.data.onGlobalUserChange = this.onGlobalUserChange.bind(this)
    app.watch('user', this.data.onGlobalUserChange)
    this.setData({
      theme: wx.getSystemInfoSync().theme || 'light',
      user: app.globalData.user,
      openid: openid,
      postActions: [
        {
          name: '互动',
          cb: e => this.go2interactCreate(e),
        }
      ]
    })

    if (wx.onThemeChange) {
      wx.onThemeChange(({theme}) => {
        this.setData({theme})
      })
    }
  },
  onUnload() {
    app.unWatch('user', this.data.onGlobalUserChange)
  },
  onGlobalUserChange(val, pre) {
    this.setData({
      user: val,
      isFollow: val.follow.includes(this.data.openid)
    })
  },
  toast(option) {
    Toast({
      context: this,
      selector: '#t-toast',
      ...option,
    });
  },
  toastHide() {
    hideToast({
      context: this,
      selector: '#t-toast',
    });
  },
  
  go2interactCreate(e) {
    wx.navigateTo({
      url: '/packageInteract/pages/create/index',
      success: (res) => {
        res.eventChannel.emit('init', { post: e })
      },
    })
  },
  getUser() {
    this.toast({
      theme: 'loading',
      direction: 'column',
      duration: 10000,
    })
    wx.cloud.callFunction({
      name: 'user',
      data: {
        action: 'get',
        data: this.data.openid
      } 
    })
    .then((res) => {
      this.setData({
        other: res.result.data[0]
      })
      this.toastHide()
    })
    .catch(() => this.toast({
      theme: 'fail',
      direction: 'column',
      message: '获取失败'
    }))
  },
  getUserInfo(e) {
    app.registerUser(e.detail.userInfo)
  },
  onSearch() {
    this.listData(true)
  },
  listData(refresh) {
    if (refresh === true) {
      this.data.noMore = false
      this.data.page = 1
      this.data.posts = []
      this.data.keyPost = {}
    }
    let { sh, page, size, noMore, keyPost, posts, openid } = this.data
    if (noMore) return
    this.setData({
      loading: {loading: true},
      page: page + 1
    })
    wx.cloud.callFunction({
      name: 'post',
      data: {
        action: 'list',
        data: {
          openid: openid,
          s: sh,
          page,
          size
        }
      }
    })
    .then(res => {
      let data = res.result.data,
      nm = data.length < size,
      _posts = []
      this.setData({
        noMore: nm,
      })
      data.forEach(i => {
        if (!keyPost[i._id]) {
          _posts.push(i)
          keyPost[i._id] = i
        }
      })
      
      if (_posts.length) {
        this.setData({
          posts: [...posts, ..._posts],
          keyPost: {...keyPost}
        })
      } else {
        this.data.noMore = nm
        this.listData()
      }
    })
    .finally(() => {
      this.setData({
        loading: {loading: false}
      })
    })
  },
  follow() {
    const { user, other, loading } = this.data
    const follow = user.follow
    const idx = follow.indexOf(other.openid)
    this.setData({
      loading: {
        ...loading,
        follow: true
      }
    })
    if (idx > -1) {
      wx.cloud.callFunction({
        name: 'user',
        data: {
          action: 'unfollow',
          data: {
            _id: user._id,
            followId: other.openid
          },
        },
      })
      .then((res) => {
        follow.splice(idx, 1)
        app.globalData.user = {
          ...user,
          follow
        }
      })
      .finally(() => {
        this.setData({
          loading: {
            ...loading,
            follow: false
          }
        })
      })
    } else {
      wx.cloud.callFunction({
        name: 'user',
        data: {
          action: 'follow',
          data: {
            _id: user._id,
            followId: other.openid
          },
        },
      })
      .then((res) => {
        follow.push(other.openid)
        app.globalData.user = {
          ...user,
          follow
        }
      })
      .finally(() => {
        this.setData({
          loading: {
            ...loading,
            follow: false
          }
        })
      })
    }
  }
})
